package com.magupe.im.web;

import com.magupe.im.web.db.service.DataService;
import com.magupe.im.web.db.service.h2.H2DataService;
import com.magupe.im.web.handler.ProtocolSelectorHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyImWeb {

	protected Logger logger = LoggerFactory.getLogger(NettyImWeb.class);
	
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 7778;

	DataService dataService = new H2DataService();

	protected void init() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			final ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap
					.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 1024) 			// 配置TCP参数，握手字符串长度设置
					.childOption(ChannelOption.TCP_NODELAY, true)
					.childHandler(new OSChannelInitializer());

			// Bind and start to accept incoming connections.
			ChannelFuture channelFuture = serverBootstrap.bind(PORT).sync();

			channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
				@Override
				public void operationComplete(Future<? super Void> future) throws Exception {

				}
			});

			// Wait until the server socket is closed.
			// In this example, this does not happen, but you can do that to gracefully
			// shut down your server.
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public class OSChannelInitializer extends ChannelInitializer<SocketChannel>{
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();
			pipeline.addLast(new ProtocolSelectorHandler(dataService));
		}
	}

	public static void main(String[] args) throws InterruptedException {
		NettyImWeb web = new NettyImWeb();
		web.init();
	}
}
